using IStrong.EC.Web.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using IStrong.EC.ExtensionMethods;
using IStrong.EC.WebApi.Results.Entity;
using IStrong.EC.WebApi.Results.Repository;
using System.Text.RegularExpressions;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace IStrong.EC.WebApi.Results.Controllers
{
    /// <summary>
    /// Api控制器模板
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : BaseController
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UserController> _logger;

        /// <summary>
        /// 配置
        /// </summary>
        private readonly IConfiguration _config;

        /// <summary>
        /// 
        /// </summary>
        private readonly IHttpClientFactory _httpClient;
        private HttpClient _client;
        /// <summary>
        /// 数据仓
        /// </summary>
        private readonly UserRep _user;
        /// <summary>
        /// 注入服务
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="config"></param>
        /// <param name="user"></param>
        /// <param name="httpClient"></param>
        public UserController(ILogger<UserController> logger, IConfiguration config, UserRep user, IHttpClientFactory httpClient)
        {
            _logger = logger;
            _config = config;
            _user = user;
            _httpClient = httpClient;
            _client = _httpClient.CreateClient("rtxUser");
            //_client.BaseAddress = new Uri(_config["userLoginUrl"]);
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="User"></param>
        /// <returns></returns>
        [HttpPost("login")]
        public async Task<JsonResult> PostLogin([FromBody] UserInfo User)
        {
            try
            {
                _logger.LogDebug("------before login");

                var Url =  $"/User/LogOn?userID={User.UserId}&password={User.PassWord}";
                var Result = await _client.GetStringAsync(Url);

                _logger.LogDebug("------login result", Result);

                if (Result == "200")
                {
                    _logger.LogDebug("------before get profile");

                    var GetUserInfoUrl = $"/User/ProfileEx?userID={User.UserId}";
                    var user = await _client.GetStringAsync(GetUserInfoUrl);

                    _logger.LogDebug("------get profile result", user);

                    return await Task.FromResult(Json(JsonConvert.DeserializeObject(user)));
                }

                return await Task.FromResult(Json(Result));

            }
            catch (Exception ex)
            {
                _logger.LogDebug("------login exception");
                _logger.LogDebug(ex.Message);

                return await Task.FromResult(Json(ex));
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        [HttpGet("userinfo")]
        public async Task<JsonResult> GetUserInfo(string UserId)
        {
            try
            {

                var GetUserInfoUrl = $"/User/ProfileEx?userID={UserId}";
                var user = _client.GetStringAsync(GetUserInfoUrl).Result;

                return await Task.FromResult(Json(JsonConvert.DeserializeObject(user)));

            }
            catch (Exception ex)
            {
                return await Task.FromResult(Json(ex));
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        [HttpGet("alluserinfo")]
        public async Task<JsonResult> GetAllUsers()
        {
            try
            {
                var data = _user.GetAllUsers();
                return await Task.FromResult(Json(data));
            }
            catch (Exception ex)
            {
                return await Task.FromResult(Json(ex));
            }
        }
        
        /// <summary>
        /// 用户信息入库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddUserInfo([FromBody] UserInfo User)
        {
            try
            {
                if (null != User.Department)
                {
                    var _Department = User.Department.Split("\\");

                    _Department.ForEach(item => {
                        if (item.Contains("组"))
                        {
                            if (item.Contains("(") || item.Contains("（"))
                            {
                                User.Department = Regex.Replace(item.Replace("（", "(").Replace("）", ")"), @"\([^\(]*\)", "");
                            }
                            else
                            {
                                User.Department = item;
                            }
                        }
                    });

                    if (User.Department.Contains("\\")) User.Department = User.Department.Split("\\")[0];
                }

                var data = _user.AddUser(User) > 0 ? true : false;

                var user = _user.GetUsers(new { UserId = User.UserId });

                return Json(user);
            }
            catch (Exception ex)
            {

                return Json(ex.Message);
            }

        }

    }
}
